﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Capokun.Models;
using System.Xml.Serialization;
using System.IO;
using System.Net;
using Capokun.Properties;
using System.Net.Mail;
using System.Configuration;
using Capokun;

namespace Capokun.Controllers
{
	public class SongController : Controller
	{
		//CapoSongs capoSongs = new CapoSongs();

		private string htmlContent(string title, string content)
		{
			///put back the <br/>

			content = content.Replace("\n\n", "<br/>");

			string returned = "";
			//add before
			returned += "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
			returned += "<html xmlns=\"http://www.w3.org/1999/xhtml\">";
			returned += "<head>";
			returned += "<title>" + title + "</title>";
			returned += "</head>";
			returned += "<body>";
			returned += "<h1>" + title + "</h1>";
			returned += content;
			//add after
			returned += "</body>";
			returned += "</html>";
			return returned;
		}

		private string cleanTitle(string title)
		{
			title = title.Replace("/", "-");
			title = title.Replace("?", "");
			title = title.Replace("\n", "");
			return title;
		}

		//public void SerializeToXML(List<Song> songs, string fileName)
		//{
		//    XmlSerializer serializer = new XmlSerializer(typeof(List<Song>));
		//    string xmlpath = Server.MapPath(Url.Content("~/Content/" + fileName));
		//    TextWriter textWriter = new StreamWriter(xmlpath);
		//    serializer.Serialize(textWriter, songs);
		//    textWriter.Close();
		//}

		//private List<Song> deserializeFromXML(string fileName)
		//{
		//    List<Song> songs = new List<Song>();
		//    string xmlpath = Server.MapPath(Url.Content("~/Content/" + fileName));

		//    if (System.IO.File.Exists(xmlpath))
		//    {
		//        XmlSerializer deserializer = new XmlSerializer(typeof(List<Song>));
		//        TextReader textReader = new StreamReader(xmlpath);
		//        songs = (List<Song>)deserializer.Deserialize(textReader);
		//        textReader.Close();
		//    }
		//    return songs;

		//}

		//public void cleanList()
		//{
		//    List<Song> songs = CapokunContext.GetAllSongs();
		//    Dictionary<string, Song> songsBySongId = new Dictionary<string, Song>();
		//    foreach (Song song in songs)
		//    {
		//        if (!songsBySongId.ContainsKey(song.SongId))
		//        {
		//            songsBySongId[song.SongId] = song;
		//        }
		//    }
		//    List<Song> returnedSongs = songsBySongId.Values.ToList();
		//    SerializeToXML(returnedSongs, "CapoSongs.xml");
		//}

		public ActionResult Create() { return View(); }

		/// <summary>
		/// language/song/create
		/// </summary>
		/// <param name="submittedSong"></param>
		/// <returns>the view of the newly created song</returns>
		[HttpPost]
		[ValidateInput(false)]
		public ActionResult Create(Song submittedSong)
		{
			///clean space at end of song title
			submittedSong.SongId = submittedSong.SongId.TrimEnd();

			if (CapokunContext.RetrieveSong(submittedSong.SongId) != null)
			{
				throw new ApplicationException("A song with the same song title already exists");
			}


			CapokunContext.CreateSong(submittedSong);
			sendMail(submittedSong);
			return new RedirectResult("../Songs/" + submittedSong.SongId);
		}

		public ActionResult Edit(string id)
		{
			///retrieves current temp songs
			List<Song> songs = CapokunContext.GetAllSongs().ToList();
			foreach (var song in songs)
			{
				if (song.SongId == id)
				{
					return View(song);
				}
			}
			return View();
		}

		[HttpPost]
		[ValidateInput(false)]
		public RedirectResult Edit(Song editedSong)
		{
			///retrieves current temp songs
			CapokunContext.UpdateSong(editedSong);
			sendMail(editedSong);
			return new RedirectResult("../../Songs/" + editedSong.SongId);
		}

		/// <summary>
		/// used in /account/admin -> javascript:delete()
		/// </summary>
		/// <param name="songId"></param>
		/// <returns>success</returns>
		public bool Delete(string songId)
		{
			CapokunContext.DeleteSong(songId);
			return true;
		}

		//    ///temporarily saves the model, wait for my validation
		//    SerializeToXML(newSongs, "CapoSongs.xml");
		//    /// 
		//    ///send mails to inform admin about new song
		//    //sendMail(submittedSong);

		//    return View("Songs", submittedSong);
		//}

		private static void sendMail(Song song)
		{
			/////send mail to contact
			//MailMessage mailSender = new MailMessage();
			//mailSender.To.Add(submittedSong.Contact.EmailAdress);
			//mailSender.From = new MailAddress(Settings.Default.mailLogin, "Capokun");
			//mailSender.IsBodyHtml = false;

			//if (submittedSong.Contact.Language == "fr" || submittedSong.Contact.Language == "fr-FR")
			//{
			//    mailSender.Subject = "[Capokun] Chanson reçu par Capokun";
			//    mailSender.Body = "Bonjour " + submittedSong.Contact.Name + "," + Environment.NewLine +
			//        "Votre chanson a bien été reçu. Vous recevrez une réponse dès que possible";
			//}
			////else if (language == "en-Gb") default language
			//else
			//{
			//    mailSender.Subject = "[Capokun] Song received by Capokun";
			//    mailSender.Body = "Hi, " + submittedSong.Contact.Name + "," + Environment.NewLine +
			//        "Your song was well received. You will get a reply as soons as possible.";
			//}

			///webmaster@capokun send irwin.lhw@gmail that new song was created
			MailMessage mail = new MailMessage();
			mail.To.Add("irwin.lhw@gmail.com");

			mail.From = new MailAddress(Settings.Default.mailLogin, "Capokun admin");
			mail.Subject = "[Capokun] Song submitted/edited by " + song.SubmittedBy + ": " + song.SongId;
			mail.Body = "<a href=\"https://www.facebook.com/" + song.SubmittedBy + "\">" + song.SubmittedBy + "</a>" + " created/submitted a song:<br/>";
			mail.Body += "<a href=\"http://www.capokun.com/en-US/songs/" + song.SongId + "\">Link to the song: " + song.SongId + "</a>";
			mail.IsBodyHtml = true;

			SmtpClient client = new SmtpClient(Settings.Default.mailSmtpServer, Settings.Default.mailSmtpServerPort);
			client.Credentials = new NetworkCredential(Settings.Default.mailLogin, Settings.Default.mailPassword);
			client.Send(mail);

		}

		/// <summary>
		/// show all songs
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public ActionResult All()
		{
			List<Song> returned = new List<Song>();
			IEnumerable<Song> songs = CapokunContext.GetAllSongs();

			returned = songs.OrderBy(x => x.SongId).ToList();
			return View(returned);
		}


		/// <summary>
		/// find a specific song
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public ActionResult Retrieve(string id)
		{
			Song returnedSong = null;
			IEnumerable<Song> songs = CapokunContext.GetAllSongs();

			foreach (Song song in songs)
			{
				if (song.SongId == id)
				{
					returnedSong = song;
					break;

				}
			}

			return View(returnedSong);
		}

		/// <summary>
		/// if id != null, it means, a specific song is asked, look for it and return it, else returns all songs
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public ActionResult Favorites()
		{
			//List<Song> returned = new List<Song>();
			//List<Song> songs = CapokunContext.GetAllSongs();
			//returned = songs.OrderBy(x => x.SongId).ToList();

			//return View(returned);
			return View();
		}

		public JsonResult GetSongContent(string songId)
		{
			IEnumerable<Song> allSongs = CapokunContext.GetAllSongs();
			foreach (Song song in allSongs)
			{
				if (songId == song.SongId)
				{
					return Json(song, JsonRequestBehavior.AllowGet);
				}
			}
			return Json("", JsonRequestBehavior.AllowGet);
		}




	}
}
